﻿using IService.Front;

namespace Service.Front
{
    public class MsgCtrlService : BaseService<TMsgCtrl>, IMsgCtrlService
    {
        public MsgCtrlService(IUnitOfWorkService unitOfWorkService) : base(unitOfWorkService)
        {
        }

        /// <summary>
        /// 添加或修改
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        public async Task<RM_ApiResult> AddOrUpdate(TMsgCtrl par)
        {
            if (par.Id == 0)
            {
                par.CreateTime = DateTime.Now;
                par.CustomerId = _CurrentCustomer?.Id;
                par.Status = 0;
            }

            var result = await AddOrUpdate(par, true);

            if (result > 0)
            {
                await _DbContext.Insertable(new TMessage
                {
                    CreateTime = DateTime.Now,
                    CustomerId = _CurrentCustomer?.Id ?? 0,
                    AboutId = result,
                    IsSend = false,
                    MsgType = Enum_MessageType.CustMsg,
                    Remark = "您有一個客戶留言待處理，請及時處理",
                    EnRemark = "You have a customer message to be processed, please deal with it in time."
                }).ExecuteCommandAsync();

                return _ResultHelper.BuildActionSuccess();
            }
            else
            {
                return _ResultHelper.BuildActionError();
            }
        }

        public async Task<RM_ApiResult> GetPageByCurrent(int pageNo, int pageSize)
        {
            //查询条件
            var where = Expressionable.Create<TMsgCtrl>().And(o => o.IsDeleted == false)
                                      .And(o => o.CustomerId == _CurrentCustomer.Id);

            var result = new RM_PageReturn<TMsgCtrl>
            {
                //查询数据
                TotalCount = await _DbContext.Queryable<TMsgCtrl>().Where(where.ToExpression()).CountAsync(),
                Datas = await _DbContext.Queryable<TMsgCtrl>()
                .Includes(u => u.MsgCtrlHandles
                .ToList(), x => x.AdminInfo)
                .Where(where.ToExpression()).OrderBy(o => o.Status).OrderByDescending(o => o.Id).ToPageListAsync(pageNo, pageSize)
            };
            //补充数据
            foreach (var item in result.Datas)
            {
                if (item.MsgCtrlHandles.Count > 0)
                {
                    var handle = item.MsgCtrlHandles.Where(h => h.IsDeleted == false).OrderByDescending(h => h.Id).First();
                    if (handle != null)
                    {
                        item.HandleTime = handle.HandleTime;
                        item.HandleDesc = handle.HandleDesc;
                        item.HandleBy = handle.AdminInfo.AdminName;
                        item.HandleAttachment = handle.HandleAttachment;
                        item.HandlePicture = handle.HandlePicture;
                    }
                }
                item.SourceDesc = _EnumHelper.GetDescription(item.Source);
                item.StatusDesc = _EnumHelper.GetDescription((Enum_MsgStatus)item.Status);
            }

            return _ResultHelper.BuildSuccess(result);
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public new async Task<RM_ApiResult> GetItem(int key)
        {
            if (await Any(key))
            {
                var data = await _DbContext.Queryable<TMsgCtrl>().Includes(u => u.MsgCtrlHandles.Where(h => h.IsDeleted == false).OrderByDescending(h => h.Id)
        .ToList(), x => x.AdminInfo).OrderBy(o => o.Status).OrderByDescending(o => o.Id).FirstAsync(o => o.Id == key);

                if (data != null)
                {
                    if (data.Customer != null)
                    {
                        data.Name = data.Customer.NickName;
                        data.Phone = data.Customer.Phone;
                        data.Email = data.Customer.Email;
                    }

                    if (data.MsgCtrlHandles.Count > 0)
                    {
                        var handle = data.MsgCtrlHandles.Where(h => h.IsDeleted == false).OrderByDescending(h => h.Id).First();
                        if (handle != null)
                        {
                            data.HandleTime = handle.HandleTime;
                            data.HandleDesc = handle.HandleDesc;
                            data.HandleBy = handle.AdminInfo.AdminName;
                            data.HandleAttachment = handle.HandleAttachment;
                            data.HandlePicture = handle.HandlePicture;
                        }
                    }

                    data.StatusDesc = _EnumHelper.GetDescription((Enum_MsgStatus)data.Status);
                    data.SourceDesc = _EnumHelper.GetDescription(data.Source);
                }

                return _ResultHelper.BuildSuccess(data);
            }
            else
            {
                return _ResultHelper.BuildError(Enum_SysAttributeType.Misc.NoData);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<RM_ApiResult> Delete(int id)
        {
            await _DbContext.DeleteNav<TMsgCtrl>(u => u.Id == id).Include(u => u.MsgCtrlHandles).ExecuteCommandAsync();
            return _ResultHelper.BuildActionSuccess();
        }
    }
}